package com.aibaixun.common.utils.file;

import com.aibaixun.common.constant.Constants;
import com.aibaixun.common.exception.ServiceException;
import com.aibaixun.common.exception.file.FileNameLengthLimitExceededException;
import com.aibaixun.common.utils.IdUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * 文件上传工具类
 *
 * @author zhangyh
 */

public class FileUploadUtils {

    private static final Logger log = LoggerFactory.getLogger(FileUploadUtils.class);
    /**
     * 默认大小 200M
     */
    public static final long DEFAULT_MAX_SIZE = 200 * 1024 * 1024;

    /**
     * 图片默认大小 200K
     */
    public static final int DEFAULT_IMAGE_LENGTH = 200 * 1024;

    /**
     * 普通压缩  500K
     */
    public static final int NORMAL_IMAGE_LENGTH = 500 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 200;


    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, String servicePath, MultipartFile file, String uploadFileName, Integer thumbType) throws IOException {
        try {
            return upload(baseDir, servicePath, file, uploadFileName, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, thumbType);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 字节数组文件上传
     *
     * @param baseDir        相对应用的基目录
     * @param servicePath    相对应用的基目录
     * @param bytes          上传的文件字节数组
     * @param uploadFileName 上传文件名称
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     */
    public static final String uploadByte(String baseDir, String servicePath, byte[] bytes, String uploadFileName)
        throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
        Exception {

        String fileName = servicePath + "/" + uploadFileName + ".png";
        File desc = getAbsoluteFile(baseDir, fileName);

        bytes = ThumbnailUtis.compressPictureForScale(bytes, FileUploadUtils.NORMAL_IMAGE_LENGTH / 1024,
            uploadFileName + ".png");
        FileUtils.writeByteArrayToFile(desc, bytes);

        String pathFileName = getPathFileName(fileName);
        return pathFileName;
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     */
    public static final String upload(String baseDir, String servicePath, MultipartFile file, String uploadFileName, String[] allowedExtension, Integer thumbType)
        throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
        Exception {
        int fileNameLength = file.getOriginalFilename().length();
        if (thumbType == null) {
            thumbType = Constants.INT_1;
        }
        if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        assertAllowed(file, allowedExtension);
        String fileName = extractFilename(servicePath, file, uploadFileName);
        File desc = getAbsoluteFile(baseDir, fileName);
        if (isImage(file)) {
            if (thumbType.intValue() == Constants.INT_1 && file.getSize() > DEFAULT_IMAGE_LENGTH) {
                byte[] bytes = file.getBytes();
                bytes = ThumbnailUtis.compressPictureForScale(bytes, FileUploadUtils.DEFAULT_IMAGE_LENGTH / 1024, file.getOriginalFilename());
                FileUtils.writeByteArrayToFile(desc, bytes);
            } else if (thumbType.intValue() == Constants.INT_2 && file.getSize() > NORMAL_IMAGE_LENGTH) {
                byte[] bytes = file.getBytes();
                bytes = ThumbnailUtis.compressPictureForScale(bytes, FileUploadUtils.NORMAL_IMAGE_LENGTH / 1024, file.getOriginalFilename());
                FileUtils.writeByteArrayToFile(desc, bytes);
            } else {
                file.transferTo(desc);
            }
        } else {
            file.transferTo(desc);
        }
        desc.setExecutable(false, false);
        desc.setWritable(true, true);
        desc.setReadable(true, false);
        String pathFileName = getPathFileName(fileName);
        return pathFileName;
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(String servicePath, MultipartFile file, String uploadFileName) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (StringUtils.isBlank(uploadFileName)) {
            fileName = servicePath + "/" + IdUtils.fastUUID() + "." + extension;
        } else {
            fileName = servicePath + "/" + uploadFileName + "." + extension;
        }
        return fileName;
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
    }

    private static final String getPathFileName(String fileName) throws IOException {
        String pathFileName = "/" + fileName;
        return pathFileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws ServiceException               文件校验异常
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
        throws FileSizeLimitExceededException, ServiceException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new ServiceException("超出文件大小限制");
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            throw new ServiceException("文件类型异常！");
        }
    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension        上传文件类型
     * @param allowedExtension 允许上传文件类型
     * @return true/false
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

    /**
     * 删除文件
     *
     * @param baseDir  基础路径
     * @param fileName 文件路径
     * @return 是否删除成功
     */
    public static boolean remove(String baseDir, String fileName) throws IOException {
        File targetFile = getAbsoluteFile(baseDir, fileName);
        return targetFile.delete();
    }

    /**
     * 删除缓存文件信息
     *
     * @param folderPath
     * @return
     */
    public static boolean removeTemp(String folderPath) {
        File folder = new File(folderPath);
        File[] listOfFiles = folder.listFiles();

        for (File file : listOfFiles) {
            if (file.isFile()) {
                file.delete();
            }
        }
        return true;
    }


    /**
     * 判断是否是图片
     *
     * @param file
     * @return
     */
    public static boolean isImage(MultipartFile file) {
        String extension = getExtension(file);
        if (Arrays.asList(MimeTypeUtils.IMAGE_EXTENSION).contains(extension.toLowerCase())) {
            return true;
        }
        return false;
    }

}
